package com.application.sistercityapplication.listadapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.main.R;
import com.application.sistercityapplication.model.Magazine;
import com.application.sistercityapplication.utils.DateUtil;
import com.artifex.mupdfdemo.MuPDFActivity;
import com.roscopeco.ormdroid.Entity;
import com.squareup.picasso.Picasso;
import com.todddavies.components.progressbar.ProgressWheel;

public class DocumentListAdapter extends BaseAdapter{
	private List<MagazineDto> _docList;
	private ViewHolder viewHolder;
	private Context _context;
	private Activity _activity;
	private MagazineDto magazineObj;
	public DocumentListAdapter(List<MagazineDto> docList,Context con,Activity activity) {
		// TODO Auto-generated constructor stub
		this._docList = docList;
		this._context = con;
		this._activity = activity;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return _docList.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return _docList.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		// TODO Auto-generated method stub
		if(convertView== null){
			viewHolder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.document_list_each_item, null);
			viewHolder.documentThumbnail = (ImageView) convertView.findViewById(R.id.documentThumbnail);
			viewHolder.countryText = (TextView) convertView.findViewById(R.id.countryName);
			viewHolder.documentTitle = (TextView) convertView.findViewById(R.id.text_item);
			viewHolder.date = (TextView) convertView.findViewById(R.id.pubDate);
			
			viewHolder.downLoadBookBtn = (ImageView) convertView.findViewById(R.id.downLoadBookBtn);
			//viewHolder.progressWheel.setVisibility(View.VISIBLE);
			convertView.setTag(viewHolder);
		}else{
			viewHolder = (ViewHolder) convertView.getTag();
		}
		magazineObj = _docList.get(position);
		try{
			
			Picasso.with(_context).load(magazineObj.getTumbnail()).into(viewHolder.documentThumbnail);
			viewHolder.countryText.setText(magazineObj.getCat());
			viewHolder.date.setText(DateUtil.convertStringToStringFormat(magazineObj.getCreated_at()));
			viewHolder.documentTitle.setText(magazineObj.getTitle());
			final Magazine mag = Entity.query(Magazine.class).where("magId").eq(magazineObj.getMagId()).execute();
			if(mag!=null){
				viewHolder.downLoadBookBtn.setVisibility(View.GONE);
				viewHolder.documentThumbnail.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Uri uri = Uri.parse(mag.path);

						Intent intent = new Intent(_activity, MuPDFActivity.class);

						intent.setAction(Intent.ACTION_VIEW);

						intent.setData(uri);

						_activity.startActivity(intent);
					}
				});
			}
			
			viewHolder.downLoadBookBtn.setOnClickListener(new DownloadDocumentClickListener(position,convertView,magazineObj));
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return convertView;
	}
	public class ViewHolder{
		private ImageView documentThumbnail;
		private TextView documentTitle;
		private TextView countryText;
		private TextView date;
		private ImageView downLoadBookBtn;
		private ProgressWheel progressWheel;
	}
	public class DownloadDocumentClickListener implements OnClickListener{
		private int _position;
		private View view;
		private MagazineDto magazineDto;
		public DownloadDocumentClickListener(int position,View btnView,MagazineDto magazineDto){
			this._position = position;
			this.view = btnView;
			this.magazineDto = magazineDto;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub'
			
			//Toast.makeText(_context, String.valueOf(_position), Toast.LENGTH_SHORT).show();
			//viewHolder.downLoadBookBtn.setImageDrawable(_activity.getResources().getDrawable(R.drawable.download_temp));
			ImageView downLoadBookBtn = (ImageView) view.findViewById(R.id.downLoadBookBtn);
			downLoadBookBtn.setVisibility(View.GONE);
			
			ProgressWheel progressWheel = (ProgressWheel) view.findViewById(R.id.pw_spinner);
			progressWheel.setVisibility(View.VISIBLE);
			DownloadTask downloadTask = new DownloadTask(_activity,progressWheel,magazineDto);
			downloadTask.execute(magazineDto.getPath());
		}
		
	}
	private class DownloadTask extends AsyncTask<String, Integer, String> {

	    private Context context;
	    private PowerManager.WakeLock mWakeLock;
	    private ProgressWheel progressWheel;
	    private MagazineDto magazineDto;
	    private String pdfPath,tumnailPath;

	    public DownloadTask(Context context,ProgressWheel progressWheel,MagazineDto magazineDto) {
	        this.context = context;
	        this.progressWheel = progressWheel;
	        this.magazineDto = magazineDto;
	    }

	    @Override
	    protected String doInBackground(String... sUrl) {
	        InputStream input = null;
	        OutputStream output = null;
	        HttpURLConnection connection = null;
	        try {
	        	File Directory = new File(
						Environment.getExternalStorageDirectory()
								+ "/SisterCity/download/Mag_"
								+ magazineDto.getMagId());
				if (!Directory.exists()) {
					Directory.mkdirs();
				}
				 URL urlPdf = new URL(magazineDto.getPath());
		            connection = (HttpURLConnection) urlPdf.openConnection();
		            connection.connect();

		            // expect HTTP 200 OK, so we don't mistakenly save error report
		            // instead of the file
		            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
		                return "Server returned HTTP " + connection.getResponseCode()
		                        + " " + connection.getResponseMessage();
		            }

		            // this will be useful to display download percentage
		            // might be -1: server did not report the length
		            int fileLength2 = connection.getContentLength();

		            // download the file
		            input = connection.getInputStream();
		            final String pdfName = magazineDto.getPath().substring(
		            		magazineDto.getPath().lastIndexOf('/') + 1,
		            		magazineDto.getPath().length());
		            File pdf = new File(Directory, pdfName);
		            output = new FileOutputStream(pdf);
		            pdfPath = pdf.getAbsolutePath();
		            byte data2[] = new byte[4096];
		            long total2 = 0;
		            int count2;
		            while ((count2 = input.read(data2)) != -1) {
		                // allow canceling with back button
		                if (isCancelled()) {
		                    input.close();
		                    return null;
		                }
		                total2 += count2;
		                // publishing the progress....
		                if (fileLength2 > 0) // only if total length is known
		                {
		                publishProgress((int) (total2 * 100 / fileLength2));
		                output.write(data2, 0, count2);
		                }else{
		                output.write(data2, 0, count2);	
		                }
		            }
				

	            if (output != null)
                    output.close();
                if (input != null)
                    input.close();
                if (connection != null)
	                connection.disconnect();
	            URL urlTumb = new URL(magazineDto.getTumbnail());
	            connection = (HttpURLConnection) urlTumb.openConnection();
	            connection.connect();

	            // expect HTTP 200 OK, so we don't mistakenly save error report
	            // instead of the file
	            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
	                return "Server returned HTTP " + connection.getResponseCode()
	                        + " " + connection.getResponseMessage();
	            }

	            // this will be useful to display download percentage
	            // might be -1: server did not report the length
	            int fileLength = connection.getContentLength();

	            // download the file
	            input = connection.getInputStream();
	            final String tumbName = magazineDto.getTumbnail().substring(
	            		magazineDto.getTumbnail().lastIndexOf('/') + 1,
	            		magazineDto.getTumbnail().length());
	            File imageThumb = new File(Directory, tumbName);
	            tumnailPath = imageThumb.getAbsolutePath();
	            output = new FileOutputStream(imageThumb);

	            byte data[] = new byte[4096];
	            long total = 0;
	            int count;
	            while ((count = input.read(data)) != -1) {
	                // allow canceling with back button
	                if (isCancelled()) {
	                    input.close();
	                    return null;
	                }
	                total += count;
	                // publishing the progress....
	                if (fileLength > 0) // only if total length is known
	                 publishProgress((int) (total * 100 / fileLength));
	                output.write(data, 0, count);
	            }
               
	        } catch (Exception e) {
	            return e.toString();
	        } finally {
	            try {
	                if (output != null)
	                    output.close();
	                if (input != null)
	                    input.close();
	            } catch (IOException ignored) {
	            }

	            if (connection != null)
	                connection.disconnect();
	        }
	        return null;
	    }
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        // take CPU lock to prevent CPU from going off if the user 
	        // presses the power button during download
	        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
	        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
	             getClass().getName());
	        mWakeLock.acquire();
	        progressWheel.spin();
	    }

	    @Override
	    protected void onProgressUpdate(Integer... progress) {
	        super.onProgressUpdate(progress);
	        // if we get here, length is known, now set indeterminate to false
	        //progressWheel.set
	      //  mProgressDialog.setMax(100);
	        //mProgressDialog.setProgress(progress[0]);
	        progressWheel.setText(progress[0]+" % ");
	        
	        if(progress[0]>= 100){
	        	progressWheel.stopSpinning();
	        	progressWheel.setVisibility(View.GONE);
	        	
	        	Magazine magazine = new Magazine();
	        	
	        	if(magazine.checkDuplicateData(magazineDto.getMagId())){
		        	magazine.id = magazine.getPk();
		        	magazine.countryId = magazineDto.getCountryId();
		        	magazine.cat = magazineDto.getCat();
		        	magazine.created_at = magazineDto.getCreated_at();
		        	magazine.magId = magazineDto.getMagId();
		        	magazine.path = pdfPath;
		        	magazine.tumbnail = tumnailPath;
		        	magazine.title = magazineDto.getTitle();
		        	magazine.updeted_at = magazineDto.getUpdeted_at();
		        	magazine.catId = magazineDto.getCatId();
		        	
		        	magazine.save();
	        	}
	        }
	    }

	    @Override
	    protected void onPostExecute(String result) {
	        mWakeLock.release();
	        //mProgressDialog.dismiss();

	       
	    }
	}
}
